/**
 * Copyright (c) 2010 CWI Amsterdam and others. All rights reserved.
 * This program and the accompanying materials are made available
 * under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    CWI Amsterdam - initial API and implementation
 */
package nl.cwi.arne.ui.jobs;

import java.io.PrintStream;

import nl.cwi.arne.generator.NetworkActivationGenerator;
import nl.cwi.arne.generator.mcrl2.ArneMCRL2Translator;
import nl.cwi.arne.ui.ArnePreferences;
import nl.cwi.arne.ui.ArneUIPlugin;

import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.ui.console.MessageConsole;

/**
 * @author Christian Krause
 */
public abstract class AbstractArneUIJob extends Job {
	
	// Print stream for mCRL2 console:
	private PrintStream mCRL2Stream;
	
	/**
	 * Default constructor.
	 * @param name Name of the job.
	 */
	public AbstractArneUIJob(String name) {
		super(name);
		setPriority(LONG);
		setUser(true);
	}
	
	/**
	 * Create an initialized ArneMCRL2Translator instance.
	 * It is initialized based on the Arne preferences.
	 * @return A new translator.
	 */
	protected ArneMCRL2Translator getInitializedTranslator() {
		ArneMCRL2Translator translator = new ArneMCRL2Translator();
		translator.setWithZeroChanges(ArnePreferences.isWithZeroChanges());
		translator.setStartFromZeroChange(ArnePreferences.isStartFromZeroChange());
		translator.setDeltaLabels(ArnePreferences.isDeltaLabels());
		translator.setVerboseLabels(ArnePreferences.isVerboseLabels());
		return translator;
	}
	
	/**
	 * Create an initialized NetworkActivationGenerator instance.
	 * It is initialized based on the Arne preferences.
	 * @return A new generator.
	 */
	protected NetworkActivationGenerator getInitializedGenerator() {
		NetworkActivationGenerator generator = new NetworkActivationGenerator();
		generator.setMCRL2Options(ArnePreferences.getMCRL2Options());
		generator.setTranslator(getInitializedTranslator());
		generator.setOutputStream(getMCRL2ConsolePrintStream());
		generator.setDebug(true);
		return generator;
	}
	
	/**
	 * Get a cached version of an mCRL2 console print stream.
	 * This returns <code>null</code> is no console was found.
	 * @return The print stream.
	 */
	protected PrintStream getMCRL2ConsolePrintStream() {
		if (mCRL2Stream==null) {
			MessageConsole console = ArneUIPlugin.getInstance().getMCRL2Console();
			if (console!=null) {
				mCRL2Stream = new PrintStream(console.newMessageStream());
			}
		}
		return mCRL2Stream;
	}
	
	/**
	 * Try to print a message to the mCRL2 console.
	 * @param message Message.
	 */
	protected void printlnToMCRL2Console(Object message) {
		getMCRL2ConsolePrintStream();
		if (mCRL2Stream!=null) {
			mCRL2Stream.println(message);
		}
	}
	
}
